package com.yunyan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunyan.entity.HistoryData;
import com.yunyan.entity.PredictData;
import com.yunyan.entity.RankData;
import com.yunyan.entity.SchoolData;
import com.yunyan.resp.JsonResp;
import com.yunyan.service.*;
import com.yunyan.util.ExcelParser;
import com.yunyan.util.predict.LevelRatioAdjustment;
import com.yunyan.util.predict.LevelRatioCheck;
import com.yunyan.util.predict.SmoothCheck;
import com.yunyan.util.predict.ValuePrediction;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/load")
public class LoadDataController {


    @Resource
    private RankService rankService;

    @Resource
    private HistoryService historyService;

    @Resource
    private SchoolService SchoolService;

    @Resource
    private MajorService majorService;

    @Resource
    private PredictService predictService;

    @GetMapping("/rank/{year}")
    public JsonResp loadRank(@PathVariable Integer year) {
        String path = System.getProperty("user.dir") + File.separator + "一分一档" + File.separator + year +".xlsx";
        List<RankData> rankData = ExcelParser.parseRank(path);
        for (RankData data : rankData) {
            data.setYear(year);
        }
        rankService.saveBatch(rankData);
        return JsonResp.ok();
    }


    @GetMapping("/history/{year}/{type}")
    public JsonResp loadHistory(@PathVariable Integer year, @PathVariable String type){
        String path = System.getProperty("user.dir") + File.separator + "文科" + File.separator + year + type +".xlsx";
        List<HistoryData> rankData = ExcelParser.parseHistory(path);
        for (HistoryData data : rankData) {
            data.setYear(year);
            data.setLevel(type);
            data.setSubject("文科");
        }
        historyService.saveBatch(rankData);
        return JsonResp.ok();
    }


    @GetMapping("/history2/{year}/{type}")
    public JsonResp loadHistory2(@PathVariable Integer year, @PathVariable String type){
        String path = System.getProperty("user.dir") + File.separator + "理科" + File.separator + year + type +".xlsx";
        List<HistoryData> rankData = ExcelParser.parseHistory(path);
        for (HistoryData data : rankData) {
            data.setYear(year);
            data.setLevel(type);
            data.setSubject("理科");
        }
        historyService.saveBatch(rankData);
        return JsonResp.ok();
    }


    @GetMapping("/school/{type}")
    public JsonResp loadSchool(@PathVariable String type){
        String path = System.getProperty("user.dir") + File.separator + "学校" + File.separator  + type + ".xlsx";
        List<SchoolData> rankData = ExcelParser.parseSchool(path);
        for (SchoolData data : rankData) {
            data.setIcon(data.getName() + ".jpg");
        }
        System.out.println(rankData.size());
        SchoolService.saveBatch(rankData);
        return JsonResp.ok();
    }

    @GetMapping("/predict")
    public JsonResp predict(){
        List<HistoryData> list = historyService.list(new LambdaQueryWrapper<HistoryData>()
                .isNotNull(HistoryData::getLowerScore)
        );


        List<RankData> rankList = rankService.list();

        Map<String, RankData> rankMap = rankList.stream().collect(Collectors.toMap(x -> x.getYear() + "," + x.getScore().replace("及以上", ""), x -> x));

        // 按照学校和专业分组
        Map<String, List<HistoryData>> collect = list.stream().collect(Collectors.groupingBy(x -> x.getCollegeName() + "," + x.getProfessorName()));
        for (Map.Entry<String, List<HistoryData>> entry : collect.entrySet()) {
            List<HistoryData> scoreList = entry.getValue();
            Map<String, List<HistoryData>> scoreMap = scoreList.stream().collect(Collectors.groupingBy(HistoryData::getSubject));
            for (Map.Entry<String, List<HistoryData>> subjectEntey : scoreMap.entrySet()) {
                List<HistoryData> subjectList = subjectEntey.getValue();
                Map<Integer, Integer> map = new HashMap<>();
                for (HistoryData historyData : subjectList) {
                    if (!map.containsKey(historyData.getYear())) {
                        map.put(historyData.getYear(), Integer.parseInt(historyData.getLowerScore()));
                    } else {
                        // 找到最小的数据
                        if (map.get(historyData.getYear()) > Integer.parseInt(historyData.getLowerScore())) {
                            map.put(historyData.getYear(), Integer.parseInt(historyData.getLowerScore()));
                        }
                    }
                }
                System.out.println(entry.getKey() + "," + subjectEntey.getKey() + "," + map);
                // 预测分数线
                int predictLine = -1;
                // 预测名次
                int predictRank = -1;

                String key1 = 2021 + "," + map.get(2021);
                String key2 = 2022 + "," + map.get(2022);
                String key3 = 2023 + "," + map.get(2023);

                RankData rank1 = rankMap.get(key1);
                RankData rank2 = rankMap.get(key2);
                RankData rank3 = rankMap.get(key3);
                if (rank1 != null && rank2 != null && rank3 != null) {
                    if (subjectEntey.getKey().equals("理科")) {
                        int [] arr = {Integer.parseInt(rank1.getPhyTotalNumber()),
                                Integer.parseInt(rank2.getPhyTotalNumber()),
                                Integer.parseInt(rank3.getPhyTotalNumber()), };
                        if (!SmoothCheck.check(arr)) {
                            if (!LevelRatioCheck.check(arr)) {
                                arr = LevelRatioAdjustment.adjust(arr);
                            }
                        }
                        predictRank = ValuePrediction.predict(arr);
                    } else {
                        int count = 0;
                        int hisRank = 0;
                            if (rank1.getHisTotalNumber() != null) {
                                count ++;
                                hisRank = hisRank + Integer.parseInt(rank1.getHisTotalNumber());
                            }
                            if (rank2.getHisTotalNumber() != null) {
                                count ++;
                                hisRank = hisRank + Integer.parseInt(rank2.getHisTotalNumber());
                            }
                            if (rank3.getHisTotalNumber() != null) {
                                count ++;
                                hisRank = hisRank + Integer.parseInt(rank3.getHisTotalNumber());
                            }

                        if (count == 3) {
                            if (entry.getKey().contains("厦门软件职业技术学院[民办],软件技术")) {
                                System.out.println("11111");
                            }
                            int [] arr = {Integer.parseInt(rank1.getHisTotalNumber()),
                                    Integer.parseInt(rank2.getHisTotalNumber()),
                                    Integer.parseInt(rank3.getHisTotalNumber()), };
                            if (!SmoothCheck.check(arr)) {
                                if (!LevelRatioCheck.check(arr)) {
                                    arr = LevelRatioAdjustment.adjust(arr);
                                }
                            }

                            predictRank = ValuePrediction.predict(arr);
                        } else {
                            if (count == 0) {
                                predictRank = 1;
                            } else {
                                predictRank = hisRank / count;
                            }
                        }
                    }

                } else {
                    int count = 0;
                    int hisRank = 0;
                    int phyRank = 0;
                    if (rank1 != null) {
                        count ++;
                        phyRank = phyRank + Integer.parseInt(rank1.getPhyTotalNumber());
                        if (rank1.getHisTotalNumber() != null) {
                            hisRank = hisRank + Integer.parseInt(rank1.getHisTotalNumber());
                        }

                    }
                    if (rank2 != null) {
                        count ++;
                        phyRank = phyRank + Integer.parseInt(rank2.getPhyTotalNumber());
                        if (rank2.getHisTotalNumber() != null) {
                            hisRank = hisRank + Integer.parseInt(rank2.getHisTotalNumber());

                        }
                    }
                    if (rank3 != null) {
                        count ++;
                        phyRank = phyRank + Integer.parseInt(rank3.getPhyTotalNumber());
                        if (rank3.getHisTotalNumber() != null) {
                            hisRank = hisRank + Integer.parseInt(rank3.getHisTotalNumber());
                        }
                    }
                    if (subjectEntey.getKey().equals("理科")) {
                        predictRank = phyRank / count;
                    } else {
                        predictRank = hisRank / count;
                    }

                }


                if (map.size() == 3) {
                    int [] arr = {map.get(2021), map.get(2022), map.get(2023)};
                    if (!SmoothCheck.check(arr)) {
                        if (!LevelRatioCheck.check(arr)) {
                            arr = LevelRatioAdjustment.adjust(arr);
                        }
                    }

                    predictLine = ValuePrediction.predict(arr);
                } else if (map.size() == 2) {
                     predictLine = (map.getOrDefault(2021, 0) +
                            map.getOrDefault(2022, 0) +
                            map.getOrDefault(2023, 0)) / 2;
                } else if (map.size() == 1) {
                     predictLine = (map.getOrDefault(2021, 0) +
                            map.getOrDefault(2022, 0) +
                            map.getOrDefault(2023, 0));
                }
                if (predictRank <= 0) {
                    predictRank = 1;
                }

                PredictData predictData = new PredictData();
                predictData.setYear(2024);
                predictData.setProfessorRank(predictRank);
                predictData.setProfessorScore(predictLine);
                String[] split = entry.getKey().split(",");
                predictData.setCollegeName(split[0]);
                predictData.setProfessorName(split[1]);
                predictData.setSubject(subjectEntey.getKey());
                // 存储到数据库
                predictService.save(predictData);
//                System.out.println("2024 年 预测的数据分数线为" +
//                        entry.getKey() + "," + subjectEntey.getKey() +
//                        "," + predictLine);
//                System.out.println("2024 年 预测的数据分数线对应的排名为" + predictRank);
            }
        }
        return JsonResp.ok();
    }


}
